package com.xiaoyu.dfs;

/**
 * @program: DS_and_A
 * @description: TODO
 * @author: YuWenYi
 * @create: 2021-06-04 11:07
 **/
public class MaxAreaOfIsland_695 {
    public static final int[][] DIRECTIONS = {{0,1},{-1,0},{0,-1},{1,0}};
    public int[][] grid;   //使用全局变量,保证全局就只有一个grid
    public int maxArea = 0;  //最大的岛屿面积
    public int area = 0;  //每个岛的面积

    public int maxAreaOfIsland(int[][] grid) {
        int row = grid.length;
        int col = grid[0].length;
        this.grid = grid;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == 1){
                    dfs(i,j);
                    area=0;
                }
            }
        }
        return maxArea;
    }

    public void dfs(int row,int col){
        //如果在边界外或者在海里,就直接返回
        if (!inGrid(row, col) || grid[row][col] == 0){
            maxArea = Math.max(maxArea, area);
            return;
        }
        //如果网格还没被走过
        if (grid[row][col] == 1){
            grid[row][col] = 2;
            area++;
            for (int[] direction : DIRECTIONS) {
                int nRow = row + direction[0];
                int nCol = col + direction[1];
                dfs(nRow, nCol);
            }
        }
    }
    public boolean inGrid(int row,int col){
        return row>=0 && row < grid.length && col>=0 && col < grid[0].length;
    }

    public static void main(String[] args) {
        int[][] grid = {
                {0,1,0,0},
                {1,0,1,0},
                {0,1,0,0},
                {1,1,0,1}
        };
        MaxAreaOfIsland_695 maxAreaOfIsland_695 = new MaxAreaOfIsland_695();
        System.out.println(maxAreaOfIsland_695.maxAreaOfIsland(grid));

    }
}
